package com.kevin.common.storage;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.kevin.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * 阿里云存储
 *
 * @author 阿沐 babamu@126.com
 * <a href="https://maku.net">MAKU</a>
 */
@Slf4j
public class AliyunStorageService extends StorageService {

    public AliyunStorageService(StorageProperties properties) {
        this.properties = properties;
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        OSS client = new OSSClientBuilder().build(properties.getAliyun().getEndPoint(),
                properties.getAliyun().getAccessKeyId(), properties.getAliyun().getAccessKeySecret());
        try {
            client.putObject(properties.getAliyun().getBucketName(), path, inputStream);
        } catch (Exception e) {
            throw new BusinessException("上传文件失败：", e);
        } finally {
            if (client != null) {
                client.shutdown();
            }
        }

        return properties.getConfig().getDomain() + "/" + path;
    }

    @Override
    public SysFileOutputStreamVO getUploadOutputStream(String fileName) {
        String path = getPath(fileName);
        File file;
        try {
            file = new File(properties.getAliyun().getBucketName() + File.separator + path);

            // 没有目录，则自动创建目录
            File parent = file.getParentFile();
            if (parent != null && !parent.mkdirs() && !parent.isDirectory()) {
                throw new IOException("目录 '" + parent + "' 创建失败");
            }
            return SysFileOutputStreamVO.builder().outputStream(new FileOutputStream(file)).url(properties.getLocal().getUrl() + "/" + path).build();
        } catch (Exception e) {
            log.info("上传文件失败:[]", e);
            throw new BusinessException("上传文件失败：", e);
        }
    }

}
